package com.tdzh.maimaiti.biz;

import android.content.Context;
import android.content.SharedPreferences;

import com.tdzh.maimaiti.util.JSONBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hisou on 2016/5/10.
 */
public class GetLocalRequest {

    public static Map<String, ?> getLocalRequest(Context context){
        SharedPreferences requestsSharedPreferences = context.getSharedPreferences("requestList", Context.MODE_PRIVATE);
        //SharedPreferences.Editor editor = requestsSharedPreferences.edit();
        Map<String, ?> localRequest = requestsSharedPreferences.getAll();
        return localRequest;
    }

    public static void saveInfo(Context context, List<Map<String, String>> dataList, String file, String key) {
        JSONArray mJsonArray = new JSONArray();
        for (int i = 0; i < dataList.size(); i++) {
            Map itemMap = dataList.get(i);
            JSONObject jsonObject = new JSONObject(itemMap);
            mJsonArray.put(jsonObject);

        }
        SharedPreferences sp = context.getSharedPreferences(file, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, mJsonArray.toString());
        System.out.println(key + mJsonArray.toString());
        editor.commit();
    }

    public static List<Map<String, String>> getInfo(Context context, String file, String key) {
        List<Map<String, String>> datas;
        SharedPreferences sp = context.getSharedPreferences(file, Context.MODE_PRIVATE);
        String result = sp.getString(key, "");
       /* try {
            JSONArray array = new JSONArray(result);
            for (int i = 0; i < array.length(); i++) {
                JSONObject itemObject = array.getJSONObject(i);
                Map itemMap = new HashMap();

                JSONArray names = itemObject.names();
                if (names != null) {
                    for (int j = 0; j < names.length(); j++) {
                        String name = names.getString(j);
                        String value = itemObject.getString(name);
                        itemMap.put(name, value);
                    }
                }
                datas.add(itemMap);
            }
        } catch (JSONException e) {

        }*/
        datas = JSONBuilder.resolveJSONArray(result);
        System.out.println("datas  " +  datas.toString());
        return datas;
    }
}
